import {PERMISSIONS} from './config'
import Cookies from 'js-cookie'
import store from '@/store'
export function isAuth (key) {
  const permissions = store.getters[PERMISSIONS] || []
  return permissions.indexOf(key) !== -1 || false
}
export function getCookie (name) {
  return Cookies.get(name)
}
export function setCookie (name, value) {
  return Cookies.set(name, value)
}
export function removeCookie (name) {
  return Cookies.remove(name)
}
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}
export function getUrlParam (name) {
  let queryString = window.location.search.substr(1) || ''
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  let resulut = queryString.match(reg)
  return resulut ? decodeURIComponent(resulut[2]) : null
}
/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}
export function isArray (obj) {
  var _arr = Object.prototype.toString.call(obj)
  if (_arr === '[object Array]') {
    return true
  } else {
    return false
  }
}
//数组排序比较函数
export function arrCompareByProp (prop) {
  return function (obj1, obj2) {
    let val1 = obj1[prop]
    let val2 = obj2[prop]
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1)
      val2 = Number(val2)
    }
    if (val1 < val2) {
      return -1
    } else if (val1 > val2) {
      return 1
    } else {
      return 0
    }
  }
}
//精确到小数点后
export function round(number, precision) {
    return Math.round(+number + 'e' + precision) / Math.pow(10, precision);
    //same as:
    //return Number(Math.round(+number + 'e' + precision) + 'e-' + precision);
}
//数值去重
export function unique (arr){
    return arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[])
}
//数组相等
export function arrEq (a, b) {
    return JSON.stringify(a.sort()) == JSON.stringify(b.sort())
}
//下划线转驼峰
export function lineToHump (str) {
  return str.replace(/\_(\w)/g, function(all, letter){
      return letter.toUpperCase()
  })
}
//驼峰转下划线
export function humpToLine (str) {
  return str.replace(/([A-Z])/g,"_$1").toLowerCase();
}
//验证非空
export function isBlank (obj) {
  if (obj === undefined || obj === null || obj === ''){
    return true
  }else if(obj instanceof Array) {
    return obj.length == 0
  }
  else if(obj instanceof Object) {
    return JSON.stringify(obj) == '{}'
  }
  return false
}
export function prefixZero (num, n) {
    return (Array(n).join(0) + num).slice(-n);
}
export function dateCompare (time1,time2) {
  let date1 = new Date(time1.slice(0,time1.indexOf(' ')))
  ,date2 = new Date(time2.slice(0,time2.indexOf(' ')))
  return date1 <= date2
}
export function occurrenceCount (str, ch) {
  if (str == null || str == '') return null
  let count = 0
  for (let i=0,j=str.length; i<j; i++) {
    if (str[i] == ch) {
      count++
    }
  }
  return count
}
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s)+}/g, (result, key) => {
    let value = formatObj[key]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}
export function parseTimeForCN (time, flag) {
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  let d = date.getDate()
  d = d < 10 ? '0' + d : d
  if (flag == 1) {
    return y+'年'+m+'月'
  }else{
    return y+'年'+m+'月'+d+'日'
  }
}
/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  Vue.cookie.delete('token')
  store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}
